package com.imy.luasupport.core;

import android.content.Context;
import android.util.Log;

import com.imy.luasupport.bridge.BridgeRegister;
import com.imy.luasupport.interfaces.IAppLoad;
import com.imy.luasupport.interfaces.ICallVirtualListener;
import com.imy.luasupport.util.LLog;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LoadState;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.ResourceFinder;
import org.luaj.vm2.lib.jse.JsePlatform;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import alscript.lua.bridge.util.app.AppLib;
import alscript.lua.bridge.util.log.LogLib;
import alscript.lua.bridge.util.system.SystemLib;

public class LuaCore implements ResourceFinder {
  private Globals mGlobals;
  public ExecutorService executorService;
  public boolean isShutdown = false;
  private static LuaCore gCore = new LuaCore();
  private ICallVirtualListener iCallVirtualListener;
  public static LuaCore get() {
    return gCore;
  }

  public ICallVirtualListener getCallVirtualListener() {
    return iCallVirtualListener;
  }

  public void setCallVirtualListener(ICallVirtualListener iCallVirtualListener){
    this.iCallVirtualListener =iCallVirtualListener;
  }
  private LuaCore() {
    executorService = Executors.newSingleThreadExecutor();
  }

  public ExecutorService getExecutorService() {
    if (isShutdown) {
      executorService = Executors.newSingleThreadExecutor();
      isShutdown = false;
    }
    return executorService;
  }

  public void stopLua() {
    executorService.shutdownNow();
    isShutdown = true;
  }
  public Context getContext() {
    return mContext;
  }
  public void init(Context context) {
    mContext = context;
    mGlobals = JsePlatform.standardGlobals();//加载基础库
    mGlobals.finder = this;
    //添加自定义基础库
    mGlobals.load(new LogLib());
    mGlobals.load(new SystemLib(this));
    mGlobals.load(new AppLib());//app基础库
    LoadState.install(mGlobals);
    LuaC.install(mGlobals);
    //调用初始化
    LuaValue loadfile = mGlobals.loadfile("Main.lua");
    //使用一个线程去执行
    //注册回调
    BridgeRegister.reg(mGlobals); // java call lua
    loadfile.call();
  }

  public IAppLoad getIAppLoad() {
    return BridgeRegister.getBridge(BridgeRegister.APP_LIFE_CYCLE);
  }

  private Context mContext;

  @Override
  public InputStream findResource(String filename) {
    try {
      Log.i("LuaCore", "findResource" + filename);
      return mContext.getAssets().open(filename);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;

  }


}
